﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using BranchOfSansar.Register.Trans;
using BranchOfSansar.Sansar.Register;
using System.IO;

namespace BranchOfSansar.Register.CallCenter
{
    public partial class frmRegCall : Form
    {
        private string TypeCode;
        private string CompanyNo;
        private vw_CallRequest Request=null;
        public BranchOfSansar.Sansar.Enquiry.vw_Contracts Contract { get; set; }

        //Засахаар орох
        public frmRegCall(vw_CallRequest req) : this(req.ReqTypeNo, req.CompanyNo)
        {
            Request = req;
            txtContractNo.Text = req.ContractNo.ToString();
            txtPhone.Text = req.PhoneNumber;
            Globals.setComboSelectedItem(txtStatus, req.StatusNo);
            Globals.setComboSelectedItem(txtLevel, req.LevelNo);

            if (!string.IsNullOrEmpty(req.Reason1))
                Globals.setComboSelectedItem(txtR1, req.Reason1);
            if (!string.IsNullOrEmpty(req.Reason2))
                Globals.setComboSelectedItem(txtR2, req.Reason2);
            if (!string.IsNullOrEmpty(req.Reason3))
                Globals.setComboSelectedItem(txtR3, req.Reason3);
            if (!string.IsNullOrEmpty(req.DistrictCode))
                Globals.setComboSelectedItem(txtDistrict, req.DistrictCode);
            if (!string.IsNullOrEmpty(req.SectionNo))
                Globals.setComboSelectedItem(txtSection, req.SectionNo);

            txtAddition.Text = req.Addition;
            txtReceivedUser.Text = req.RecvUser;
            if (req.UserNoOfDid != null)
                Globals.setComboSelectedItem(txtDidUserNo, req.UserNoOfDid ?? 0);
            if (req.UserNoOfClosed != null)
                Globals.setComboSelectedItem(txtClosedUserNo, req.UserNoOfClosed ?? 0);

            txtReceivedDate.DateTime = req.DateOfReceived;
            if (req.DateOfPlaning != null)
                txtDueDate.DateTime = req.DateOfPlaning ?? DateTime.Now;
            if (req.DateOfClosed != null)
                txtClosedDate.DateTime = req.DateOfClosed ?? DateTime.Now;

            btnCreate.Text = "Хадгалах";
            btnCreate.Enabled = false;
            btnComment.Enabled = true;
            btnClose.Enabled = true;
            CommentBind();

        }

        //Шинээр дуудлага орууулах
        public frmRegCall(string type_code, string company_no)
        {
            this.CompanyNo = company_no;
            this.TypeCode = type_code;
            InitializeComponent();
            txtReceivedUser.Text = Globals.UserName;
            txtReceivedDate.DateTime = DateTime.Now;
            txtDueDate.DateTime = DateTime.Now;
            BranchOfSansar.Sansar.Enquiry.Parameter[] paras;

            using (BranchOfSansar.Sansar.Enquiry.EnquiryClient ec = new Sansar.Enquiry.EnquiryClient(Globals.Token))
            {
                paras = ec.Parameters("it.GroupCode='CS' OR it.GroupCode='CL' OR it.GroupCode='R1' OR it.GroupCode='R2' OR it.GroupCode='R3' OR it.GroupCode='R4' OR it.GroupCode='R5' ");

                var usr = ec.Users("it.PositionNo='E'").ToList();

                txtDidUserNo.Properties.Items.AddRange(usr
                    .Select(s => new BranchOfSansar.Sansar.Enquiry.ComboItem() { IntValue = s.UserId, Display = s.Name })
                    .ToArray());
                Globals.setComboSelectedItem(txtDidUserNo, 0);


                txtClosedUserNo.Properties.Items.AddRange(usr
                    .Select(s => new BranchOfSansar.Sansar.Enquiry.ComboItem() { IntValue = s.UserId, Display = s.Name })
                    .ToArray());
                Globals.setComboSelectedItem(txtClosedUserNo, 0);

                txtStatus.Properties.Items.AddRange(paras
                    .Where(w => w.GroupCode == "CS")
                    .Select(s => new BranchOfSansar.Sansar.Enquiry.ComboItem() { StrValue = s.ParaCode, Display = s.Name })
                    .ToArray());
                Globals.setComboSelectedItem(txtStatus, "NEW");

                txtLevel.Properties.Items.AddRange(paras
                    .Where(w => w.GroupCode == "CL")
                    .Select(s => new BranchOfSansar.Sansar.Enquiry.ComboItem() { StrValue = s.ParaCode, Display = s.Name })
                    .ToArray());
                Globals.setComboSelectedItem(txtLevel, "NOR");

                txtR1.Properties.Items.AddRange(paras
                   .Where(w => w.GroupCode == "R1")
                   .Select(s => new BranchOfSansar.Sansar.Enquiry.ComboItem() { StrValue = s.ParaCode, Display = s.Name })
                   .ToArray());
                txtR1.SelectedIndex = 0;

                txtR2.Properties.Items.AddRange(paras
                   .Where(w => w.GroupCode == "R2")
                   .Select(s => new BranchOfSansar.Sansar.Enquiry.ComboItem() { StrValue = s.ParaCode, Display = s.Name })
                   .ToArray());
                txtR2.SelectedIndex = 0;

                txtR3.Properties.Items.AddRange(paras
                   .Where(w => w.GroupCode == "R3")
                   .Select(s => new BranchOfSansar.Sansar.Enquiry.ComboItem() { StrValue = s.ParaCode, Display = s.Name })
                   .ToArray());
                txtR3.SelectedIndex = 0;

                txtDistrict.Properties.Items.AddRange(paras
                   .Where(w => w.GroupCode == "R4")
                   .Select(s => new BranchOfSansar.Sansar.Enquiry.ComboItem() { StrValue = s.ParaCode, Display = s.Name })
                   .ToArray());
                txtDistrict.SelectedIndex = 0;

                txtSection.Properties.Items.AddRange(paras
                   .Where(w => w.GroupCode == "R5")
                   .Select(s => new BranchOfSansar.Sansar.Enquiry.ComboItem() { StrValue = s.ParaCode, Display = s.Name })
                   .ToArray());
                txtSection.SelectedIndex = 0;

            }


        }

        private string FileName
        {
            get { return string.Format("frmRegCall{0}{1}.xml", this.CompanyNo, this.TypeCode); }
        }


        private void frmRegCall_Load(object sender, EventArgs e)
        {
            if (File.Exists("Cust" + FileName))
                layCustomer.RestoreLayoutFromXml("Cust" + FileName);
            if (File.Exists(FileName))
                layMain.RestoreLayoutFromXml(FileName);
            if (File.Exists("Add" + FileName))
                layAddInfo.RestoreLayoutFromXml("Add" + FileName);
            if (File.Exists("Main" + FileName))
                layMainInfo.RestoreLayoutFromXml("Main" + FileName);

        }

        private void layMain_HideCustomization(object sender, EventArgs e)
        {
            layMain.SaveLayoutToXml(FileName);
        }

        private void layAddInfo_HideCustomization(object sender, EventArgs e)
        {
            layAddInfo.SaveLayoutToXml("Add" + FileName);
        }

        private void layMainInfo_HideCustomization(object sender, EventArgs e)
        {
            layMainInfo.SaveLayoutToXml("Main" + FileName);
        }

        private void layCustomer_HideCustomization(object sender, EventArgs e)
        {
            layCustomer.SaveLayoutToXml("Cust" + FileName);
        }

        protected void FillData()
        {
            txtContractNo.Text = this.Contract.ContractNo.ToString();
            txtDescription.Text = string.Format("{2},{3} {0} байр {1} тоот", Contract.ApartNo1, Contract.DoorNo, Contract.CustName, Contract.CustRegister);
        }

        private void txtContractNo_ButtonClick(object sender, DevExpress.XtraEditors.Controls.ButtonPressedEventArgs e)
        {
            BranchOfSansar.Register.Main.frmContractList frm = new BranchOfSansar.Register.Main.frmContractList(true);
            if (frm.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                this.Contract = frm.Contract;
                FillData();
            }
        }
        protected void SetContractNo(long cno)
        {
            using (BranchOfSansar.Sansar.Enquiry.EnquiryClient tc = new Sansar.Enquiry.EnquiryClient(Globals.Token))
            {
                var res = tc.ContractDetail(cno);
                if (res == null)
                {
                    txtDescription.Text = "Гэрээний дугаар буруу";
                    Contract = null;
                    return;
                }
                this.Contract = res;
                FillData();
            }

        }
        protected void SetContractNo(string uname)
        {
            using (BranchOfSansar.Sansar.Enquiry.EnquiryClient tc = new Sansar.Enquiry.EnquiryClient(Globals.Token))
            {
                var res = tc.ContractDetailByUser(uname);
                if (res == null)
                {
                    txtDescription.Text = "Хэрэглэгчийн дугаар буруу";
                    Contract = null;
                    return;
                }
                this.Contract = res;
                FillData();
            }

        }

        private void txtContractNo_KeyUp(object sender, KeyEventArgs e)
        {
            long num;
            if (e.KeyCode == Keys.Enter)
            {
                if (long.TryParse(txtContractNo.Text, out num))
                    SetContractNo(num);
                else
                    SetContractNo(txtContractNo.Text);
            }
        }

        private void btnTransfers_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            if (Contract != null)
            {
                frmTransactionList frm = new frmTransactionList(Contract.ContractNo);
                frm.Show();
            }
        }

        private CallRequest GetData()
        {

            CallRequest result = new CallRequest()
                       {
                           Addition = txtAddition.Text,
                           CompanyNo = CompanyNo,
                           DateOfPlaning = txtDueDate.DateTime,
                           DateOfReceived = txtReceivedDate.DateTime,
                           LevelNo = ((BranchOfSansar.Sansar.Enquiry.ComboItem)txtLevel.SelectedItem).StrValue,
                           StatusNo = ((BranchOfSansar.Sansar.Enquiry.ComboItem)txtStatus.SelectedItem).StrValue,
                           PhoneNumber = txtPhone.Text,
                           ReqTypeNo = TypeCode,
                           UserNoOfClosed = ((BranchOfSansar.Sansar.Enquiry.ComboItem)txtClosedUserNo.SelectedItem).IntValue,
                           UserNoOfDid = ((BranchOfSansar.Sansar.Enquiry.ComboItem)txtDidUserNo.SelectedItem).IntValue,
                           UserNoOfReceived = Globals.UserId,
                       };

            if (txtR1.SelectedIndex > 0)
                result.Reason1 = txtR1.Text;

            if (txtR2.SelectedIndex > 0)
                result.Reason2 = txtR2.Text;

            if (txtR3.SelectedIndex > 0)
                result.Reason3 = txtR3.Text;

            if (txtDistrict.SelectedIndex > 0)
                result.DistrictCode = txtDistrict.Text;

            if (txtSection.SelectedIndex > 0)
                result.SectionNo = txtSection.Text;

            if (txtClosedDate.Text != "")
                result.DateOfClosed = txtClosedDate.DateTime;
            if (Contract != null)
            {
                result.ContractNo = Contract.ContractNo;
            }

            return result;
        }

        private void btnCreate_Click(object sender, EventArgs e)
        {
            CallRequest value = GetData();

            using (RegisterClient rc = new RegisterClient(Globals.Token))
            {
                Result res;
                if (Request == null)
                {
                    res = rc.AddCallRequest(value);
                }
                else
                {
                    value.ReqNo = Request.ReqNo;
                    res = rc.EditCallRequest(value);
                    btnCreate.Enabled = false;
                }

                if (res.Code != 0)
                    Globals.Warr(res.Message);
                else
                {
                    Globals.Info(res.Message);
                    this.DialogResult = System.Windows.Forms.DialogResult.OK;
                }
            }
        }

        private void Field_EditValueChanged(object sender, EventArgs e)
        {
            btnCreate.Enabled = true;
        }


        private void CommentBind()
        {
            using (RegisterClient reg = new RegisterClient(Globals.Token))
            {
                gridComment.DataSource = reg.CommentList(Request.ReqNo);
            }
        }
        
        private void btnComment_Click(object sender, EventArgs e)
        {
            frmComment frm = new frmComment(Request.ReqNo);
            if (frm.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                txtStatus.Text = "Хийдэж байгаа";                
                CommentBind();
            }
        }

        private void gridComment_DoubleClick(object sender, EventArgs e)
        {
            if (viewComment.SelectedRowsCount > 0)
            {
                var item = (CommentRow)viewComment.GetRow(viewComment.GetSelectedRows()[0]);
                frmComment frm = new frmComment(item);
                if (frm.ShowDialog() == System.Windows.Forms.DialogResult.OK)
                {
                    CommentBind();
                }
            }
        }

        private void frmRegCall_FormClosing(object sender, FormClosingEventArgs e)
        {
            if (btnCreate.Enabled)
            {
                if (Globals.Question("Та өөрчлөлтийг хадгалах уу?") == System.Windows.Forms.DialogResult.Yes)
                {
                    btnCreate_Click(null, null);
                }
            }
        }

        private void btnClose_Click(object sender, EventArgs e)
        {
            frmClose frm = new frmClose(Request.ReqNo);
            if (frm.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                txtStatus.Text = "Хаасан";
                CommentBind();
            }
        }



    }
}
